package top.mable.payment.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.mable.payment.service.OrderService;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 使用过期队列
     * @param userId
     * @param productId
     * @param num
     */
    @Override
    public void makeOrder(String userId, String productId, Integer num) {

        String orderId = UUID.randomUUID().toString();
        log.info("订单已经生成orderid={}",orderId);

        String exchangeName = "ttl_direct_exchange";
        String routingKey = "ttl";
        HashMap args = new HashMap();
        args.put("orderId",orderId);
        args.put("userId",userId);
        args.put("productId",productId);
        args.put("num",num);

        HashMap totalArgs = new HashMap();
        totalArgs.put("args",args);
        //真正需要消费消息的地方
        totalArgs.put("exchangeName",exchangeName);
        totalArgs.put("routingKey",routingKey);

        // 先把消息丢到一个队列中，但是该队列没有对呀的监听，而且设置有有效时间
        rabbitTemplate.convertAndSend(exchangeName,routingKey,totalArgs);
    }

    @Override
    public void makeTtlMsgOrder(String userId, String productId, Integer num) {

        String orderId = UUID.randomUUID().toString();
        log.info("订单已经生成orderid={}",orderId);

        String exchangeName = "ttl_direct_exchange";
        String routingKey = "ttl.msg";

        //给消息设置过期时间
        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("5000");
                message.getMessageProperties().setContentEncoding("utf-8");
                return message;
            }
        };

        rabbitTemplate.convertAndSend(exchangeName,routingKey,orderId,messagePostProcessor);
    }
}
